from django.shortcuts import render
import os
import json
import time
from django.conf import settings
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from .emotion_sys.unified_emotion_classifier import VideoEmotionRecognizer


def save_result_to_json(result_data):
    """保存结果到 result.json 文件"""
    json_file_path = os.path.join(os.path.dirname(__file__), 'result.json')

    # 读取现有数据（如果文件存在）
    existing_results = []
    if os.path.exists(json_file_path):
        try:
            with open(json_file_path, 'r', encoding='utf-8') as f:
                existing_results = json.load(f)
        except:
            existing_results = []

    # 添加新结果
    existing_results.append(result_data)

    # 保存到文件
    with open(json_file_path, 'w', encoding='utf-8') as f:
        json.dump(existing_results, f, ensure_ascii=False, indent=2)


def get_results_from_json():
    """从 result.json 文件读取所有结果"""
    json_file_path = os.path.join(os.path.dirname(__file__), 'result.json')
    if os.path.exists(json_file_path):
        try:
            with open(json_file_path, 'r', encoding='utf-8') as f:
                return json.load(f)
        except:
            return []
    return []


def delete_file(filepath):
    """安全删除指定文件"""
    try:
        if os.path.exists(filepath):
            os.remove(filepath)
            return True
        return False
    except Exception as e:
        print(f"删除文件失败: {e}")
        return False


@csrf_exempt
def upload_mp4(request):
    if request.method == 'POST' and request.FILES.get('mp4_file'):
        mp4_file = request.FILES['mp4_file']
        save_dir = os.path.join(settings.MEDIA_ROOT, 'emotion_uploads')
        os.makedirs(save_dir, exist_ok=True)
        save_path = os.path.join(save_dir, mp4_file.name)
        try:
            # 1. 保存文件
            with open(save_path, 'wb+') as destination:
                for chunk in mp4_file.chunks():
                    destination.write(chunk)
            # 2. 对视频进行处理
            result = handle_emotion_recognition(save_path)
            # 3. 处理后删除文件
            delete_file(save_path)

            # 4. 保存结果到 JSON 文件
            result_data = {
                'id': len(get_results_from_json()) + 1,
                'filename': mp4_file.name,
                'size': f"{mp4_file.size / (1024 * 1024):.2f} MB",
                'emotion': result.get('main_emotion_label', 'unknown'),
                'confidence': result.get('total_frames_analyzed', 0),
                'timestamp': time.strftime('%Y-%m-%d %H:%M:%S')
            }
            save_result_to_json(result_data)

            return JsonResponse({'status': 'success', 'result': result})
        except Exception as e:
            return JsonResponse({'status': 'fail', 'error': str(e)})
    elif request.method == 'GET':
        return render(request, 'sentiment.html')
    return JsonResponse({'status': 'fail', 'error': 'No file uploaded'})


def get_results(request):
    """获取所有分析结果的 API"""
    results = get_results_from_json()
    return JsonResponse({'results': results})


def handle_emotion_recognition(file_path):
    recognizer = VideoEmotionRecognizer()  # 可加 interval 参数
    result = recognizer.process_file(file_path)
    return result
